export function isAllLatin(str: string) {
	const reg = new RegExp("^[a-zA-Z0-9]+$");
	return reg.test(str);
}

export function smartCompareStr(a: string, b: string) {
	if (a.length !== b.length) {
		return a.length - b.length;
	}

	if (isAllLatin(a) && !isAllLatin(b)) {
		return -1;
	}

	if (!isAllLatin(a) && isAllLatin(b)) {
		return 1;
	}

	return a.localeCompare(b);
}

export function sortStringArr(arr: string[]) {
	return arr.sort((a, b) => smartCompareStr(a, b));
}

export function setTagDivHeight() {
	const trList = document.querySelectorAll("#show-info tr");
	for (let i = 0; i < trList.length; i++) {
		const tr = trList[i] as HTMLElement;
		const td = tr.firstElementChild as HTMLElement;
		if (td && tr) {
			tr.style["height"] = "auto";
			td.style["height"] = "inherit";
			tr.style["height"] = Math.floor(tr.scrollHeight) + "px";
		}
	}
}

export function splitFilename(file: string) {
	const index = file.lastIndexOf(".");

	const ext = file.slice(index);
	const name = file.slice(0, index);
	return {
		ext,
		name,
	};
}

export function getPurename(filename: string) {
	const index = filename.lastIndexOf(".");
	if (index) {
		return filename.slice(0, index);
	}
	return filename;
}

function randomSection(min: number, max: number) {
	return min + Math.round(Math.random() * (max - min));
}

export function randomIndex(len: number, rejectNumbers: number[] = []) {
	let index = randomSection(0, len);

	while (rejectNumbers.includes(index)) {
		index = randomSection(0, len);
	}

	return index;
}

export function randomItemFromArr<T>(arr: T[], rejectNumbers: number[] = []) {
	const index = randomIndex(arr.length - 1, rejectNumbers);
	return arr[index];
}

export function mapAllowRange(arr: string[]) {
	const res: number[] = [];

	if (arr.includes("平假名")) {
		res.push(0);
	}

	if (arr.includes("片假名")) {
		res.push(1);
	}

	if (arr.includes("罗马字")) {
		res.push(2);
	}

	return res;
}
